#include "BlockNet.h"
#include "Log.h"


CTempNet::CTempNet()
    :m_iLen(0),m_iConnectFlag(EnmNetState::ENM_INIT)
{
    memset(m_csBuffer, 0, sizeof(m_csBuffer));
}

CTempNet::~CTempNet()
{
}

const char * CTempNet::GetRecvBuffer(int &iLen) const
{
    if( m_iConnectFlag == 1)
    iLen = m_iLen;
    return m_csBuffer;
}

void CTempNet::ClearRecvBuffer()
{
    memset(m_csBuffer, 0, sizeof(m_csBuffer));
    m_iLen = 0;
}

int CTempNet::GetConnectFlag() const
{
    return m_iConnectFlag;
}

bool CTempNet::OnPacket(const int iSocket, char *pData, int iLen)
{
    if (false == CNetBase::OnPacket(iSocket, pData, iLen))
    {
        return false;
    }
    if (iLen >= MAX_RECV_BUFFER_LEN)
    {
        LOG_ERR("receive too long chars. size:%d", iLen);
        return false;
    }

    memcpy(m_csBuffer, pData, iLen);
    m_csBuffer[iLen] = '\0';
    return true;
}

bool CTempNet::OnConnect(const int iSocket)
{
    if (false == CNetBase::OnConnect(iSocket))
    {
        return false;
    }
    m_iConnectFlag = EnmNetState::ENM_CONNECTED;
    return true;
}

bool CTempNet::OnClose(const int iSocket)
{
    if (false == CNetBase::OnClose(iSocket))
    {
        return false;
    }

    m_iConnectFlag = EnmNetState::ENM_INIT;
    return true;
}


BlockNet::BlockNet()
    :m_oTempNet(),m_iConnectSocket(-1)
{
}


BlockNet::~BlockNet()
{
    if (m_iConnectSocket != -1)
    {
        m_oTempNet.Close(m_iConnectSocket);
        m_iConnectSocket = -1;
    }
}

bool BlockNet::Init()
{
    if (!m_oTempNet.Init())
    {
        return false;
    }

    m_iConnectSocket = -1;
    return true;
}

int BlockNet::Connect(const char *pIp, int iPort, int iWaitTime)
{
    if (m_iConnectSocket != -1)
    {
        m_oTempNet.Close(m_iConnectSocket);
        m_iConnectSocket = -1;
    }

    m_iConnectSocket = m_oTempNet.AddConnect(pIp, iPort);
    if (-1 == m_iConnectSocket)
    {
        //创建套接字失败
        return -1;
    }

    m_oTempNet.Polling(iWaitTime);
    
    if( m_oTempNet.GetConnectFlag() == EnmNetState::ENM_INIT)
    {
        return -1;
    }
    return 0;
}

int BlockNet::SendAndRecv(const char *pSendData, int iSendLen, const char *pRecvData, int &iRecvLen, int iWaitTime)
{
    if (m_iConnectSocket == -1)
    {
        //连接断开
        return -1;
    }

    m_oTempNet.ClearRecvBuffer();

    if (m_oTempNet.Send(m_iConnectSocket, pSendData, iSendLen) <= 0)
    {
        //发送失败
        return -1;
    }

    if (m_oTempNet.Polling(iWaitTime) <= 0)
    {
        //没收到回报
        return -1;
    }

    int iLen = 0;
    const char *pBuff = m_oTempNet.GetRecvBuffer(iLen);
    if (iLen == 0)
    {
        return -1;
    }

    pRecvData = pBuff;
    iRecvLen = iLen;

    return 0;

}


void BlockNet::Close(const int iSocket)
{
    m_oTempNet.Close(iSocket);
}
